package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;


/**
 * @Description: dwm层 用户跳出明细计算
 * @Author: tiancy
 * @Create: 2021/11/29
 */
public class UserJumpDetailApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 设置流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);

        //TODO 2.设置检查点(略)

        //TODO 3.从Kafka中读取数据
        //3.1 声明消费主题以及消费者组
        String topic = "dwd_page_log";
        String groupId = "user_jump_detail_app_group";

        //3.2 创建消费者对象
        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);

        //3.3 消费数据封装流
        DataStreamSource<String> kafkaDS = env.addSource(kafkaSource);
        // kafkaDS.print("Kafka_dwd_page_log ===> ");

        //TODO 4.对流中的数据进行类型转换   jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        //TODO 5.指定watermark以及提取事件时间字段
        SingleOutputStreamOperator<JSONObject> jsonObjWithWatermarkDS = jsonObjDS.assignTimestampsAndWatermarks(
                //WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
                WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject jsonObj, long recordTimestamp) {
                                        return jsonObj.getLong("ts");
                                    }
                                }
                        )
        );

        //jsonObjWithWatermarkDS.print(">>>>>>");

        //TODO 6. 按照mid进行分组
        KeyedStream<JSONObject, String> keyedDS = jsonObjWithWatermarkDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));
        //keyedDS.print(">>>>>>******>>>>>>");
        //TODO 7. 使用FlinkCEP 按照指定的pattern，从流中将匹配的数据过滤处理
        //7.1 定义pattern
        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("first").where(
                new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) {
                        //获取lastpageId
                        String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                        return lastPageId == null || lastPageId.length() == 0;
                    }
                }
        ).next("second").where(
                new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) {
                        String pageId = jsonObj.getJSONObject("page").getString("page_id");
                        return pageId != null && pageId.length() > 0;
                    }
                }
        ).within(Time.seconds(10));

        //7.2 将pattern应用到流上
        PatternStream<JSONObject> patternDS = CEP.pattern(keyedDS, pattern);

        //7.3 从流中提取数据
        /** 先定义一个侧输出流标签 timeOutTag. */
        OutputTag<String> timeOutTag = new OutputTag<String>("timeOutTag") {
        };
        SingleOutputStreamOperator<String> resDS = patternDS.flatSelect(
                timeOutTag,
                // 用来处理超时时间的数据,并将超时数据写到侧输出流中.
                new PatternFlatTimeoutFunction<JSONObject, String>() {
                    @Override
                    public void timeout(Map<String, List<JSONObject>> paten, long l, Collector<String> out) throws Exception {
                        List<JSONObject> jsonObjectList = paten.get("first");
                        for (JSONObject jsonObject : jsonObjectList) {
                            //注意：将和first匹配的元素(跳出行为) 向下游传递   out.collect将超时元素放到侧输出流中
                            out.collect(jsonObject.toString());
                        }
                    }
                },
                new PatternFlatSelectFunction<JSONObject, String>() {
                    @Override
                    public void flatSelect(Map<String, List<JSONObject>> map, Collector<String> collector) throws Exception {
                        /** 完全满足我们定义的模板 --> 是跳转数据,这里不处理就可以. 处理完全匹配的数据   如果完全匹配的数据，属于跳转 不在我们的需求范围内，所以这个方法中不需要有什么实现 */
                    }
                }
        );

        // 8、从侧输出流中获取跳出明细
        DataStream<String> timeoutDS = resDS.getSideOutput(timeOutTag);

        timeoutDS.print(">>>>>>");

        //TODO 8.将跳出明细数据写到kafka主题中
        timeoutDS.addSink(MyKafkaUtil.getKafkaSink("dwm_user_jump_detail"));
        /**
         测试需要启动的服务 :
         数据来源 : dwd_page_log
         启动的服务 : rt_logger.sh start(数据采集服务 + nginx) | `BaseLogApp` .  /opt/module/applog_realtime/gmall2020-mock-log-2020-12-18.jar .zk、Kafka、HDFS
         */
        env.execute();
    }

}